package com.iwhalecloud.citybrain.flow.platform.manager.application.common.command;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.citybrain.flow.platform.manager.common.client.HttpSetParticipantsDto;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.common.impl.interceptor.Command;
import org.flowable.engine.common.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.runtime.ProcessInstance;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;

/**
 * @author cheng.huaxing
 * @date 2019-03-19
 */
public class SetParticipantsCmd implements Command<ProcessInstance>, Serializable {
    private static final long serialVersionUID = -7335295538535987762L;

    private HttpSetParticipantsDto setParticipantsDto;

    public SetParticipantsCmd(HttpSetParticipantsDto setParticipantsDto) {
        this.setParticipantsDto = setParticipantsDto;
    }

    @Override
    public ProcessInstance execute(CommandContext commandContext) {
        RuntimeService runtimeService = CommandContextUtil.getProcessEngineConfiguration(commandContext).getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(setParticipantsDto.getProcessInstanceId()).active().singleResult();
        if (Objects.nonNull(processInstance)) {
            setProcessInstanceVariable(processInstance, setParticipantsDto.getTacheList());
        }
        return processInstance;
    }

    private void setProcessInstanceVariable(ProcessInstance processInstance, Map<String, Object> tacheList) {
        if (tacheList != null && !tacheList.isEmpty()) {
            for (Map.Entry<String, Object> entry : tacheList.entrySet()) {
                JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(entry.getValue()));
                JSONArray jsonArray = jsonObject.getJSONArray("PARTICIPANTS");
                if (Objects.nonNull(jsonArray)) {
                    StringBuilder participantIds = new StringBuilder();
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject participant = jsonArray.getJSONObject(i);
                        if (i == 0) {
                            participantIds.append(participant.getString("participantId"));
                        } else {
                            participantIds.append(",").append(participant.getString("participantId"));
                        }
                    }
                    ((ExecutionEntity) processInstance).setVariable(entry.getKey(), participantIds.toString());
                }
            }
        }
    }
}
